package com.smcaiot.filesync.starter.app;

import com.smcaiot.filesync.starter.task.FileSyncTask;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executors;

/**
 * 多线程执行定时任务
 */
@Configuration
@ConditionalOnProperty(name = "filesync.parallel", havingValue = "true")
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        Method[] methods = FileSyncTask.class.getDeclaredMethods();
        Long count = Arrays.stream(methods).filter(m -> Objects.nonNull(m.getAnnotation(Scheduled.class))).count();
        int mc = Math.toIntExact(Optional.ofNullable(count).orElse(3L));
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(mc));
    }

}
